package com.devframe.sys.util.cglib;

import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import net.sf.cglib.core.Converter;

/**
 * 版权所有：福建邮科电信业务部厦门研发中心 ====================================================
 * 文件名称: MyConverter.java 修订记录： No 日期 作者(操作:具体内容) 1. 2013-1-12
 * 詹保山（softzbs@126.com）(创建:创建文件)
 * ====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 * 
 */
public class MyConverter implements Converter {

	private Object fromObject;

	private Object toObject;

	private MyBeanCopier myBeanCopier;

	private Map<String, Method> fieldGeterMap;

	public MyConverter(Object fromObject, Object toObject,
			MyBeanCopier myBeanCopier) {
		super();
		this.fromObject = fromObject;
		this.toObject = toObject;
		this.myBeanCopier = myBeanCopier;
		this.fieldGeterMap = this.myBeanCopier.accessBeanFiledGetMethod(toObject.getClass().getName());
	}
	
	private boolean isPrimitveNumberType(Class clazz) {// zhanbs add
		if (clazz.isPrimitive()  
				&&( clazz.equals(int.class) || clazz.equals(long.class)
				|| clazz.equals(double.class) || clazz.equals(float.class)
				|| clazz.equals(byte.class)
				|| clazz.equals(short.class))
				) {
			return true;
		}
		return false;
	}

	public Object convert(Object value, Class target, Object context) {
		try {
			if (value == null) {
				String name = context.toString().substring(3);
				Method method = this.fieldGeterMap.get(name.toUpperCase());
				return method.invoke(toObject, null);
			} else if (isPrimitveNumberType(target)&& StringUtils.equals("0", value.toString())) {
				String name = context.toString().substring(3);
				Method method = this.fieldGeterMap.get(name.toUpperCase());
				return method.invoke(toObject, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

}
